package xcmg.device.service.order;


import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xcmg.device.dao.entity.order.GpsMmSwOrderLabelDO;
import xcmg.device.dao.mapper.order.GpsMmSwOrderLabelMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.service.vo.order.GpsMmSwOrderLabelVO;
import xcmg.device.service.vo.order.GpsMmSwOrderVO;
import xcmg.syn.feign.SynClient;
import xcmg.syn.service.vo.order.MmSwOrderLabelVO;
import yb.ecp.fast.infra.infra.ActionResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Slf4j
@Service
public class GpsMmSwOrderLabelService {

    @Autowired
    private SynClient synClient;
    @Autowired
    private GpsMmSwOrderLabelMapper gpsMmSwOrderLabelMapper;
    @Autowired
    private GpsMmSwOrderService gpsMmSwOrderService;

    @Autowired
    private SubcontractingOrderService subcontractingOrderService;

    private static final int BATCH_SIZE = 5000;

    public void doSyncGpsMmSwOrderLebel(Date t, String querySupplierNo) {
        log.info("doSyncGpsMmSwOrderLebel,t:{},querySupplierNo:{}", t, querySupplierNo);
        MmSwOrderLabelVO voParam = new MmSwOrderLabelVO();
        Long maxId = null;
        while (true) {
            //如果有时间，根据时间增量同步
            voParam.setLastModifiedTimeStart(t);
            voParam.setLimitNum(BATCH_SIZE);
            voParam.setSupplierNo(querySupplierNo);
            voParam.setMinId(maxId);
            voParam.setDelFlg("0");
            ActionResult<List<MmSwOrderLabelVO>> listActionResult = synClient.queryLabelList(voParam);
            if (listActionResult.getCode() != 0) {
                log.error("同步GPS数据失败,voParam：{},\n listActionResult:{}", voParam, listActionResult);
                break;
            }
            List<MmSwOrderLabelVO> labels = listActionResult.getValue();
            if (CollectionUtils.isEmpty(labels)) {
                log.info("没有需要同步的GPS数据");
                break;
            }
            boolean fullPage = (labels.size() == BATCH_SIZE);
            maxId = labels.get(labels.size() - 1).getId();

            Set<Long> orderIds = labels.stream().map(MmSwOrderLabelVO::getOrderId).collect(Collectors.toSet());
            Map<Long, GpsMmSwOrderVO> orderMap = gpsMmSwOrderService.queryMaps(new ArrayList<>(orderIds));
            List<GpsMmSwOrderLabelDO> okList = new ArrayList<>(labels.size());
            for (MmSwOrderLabelVO labelVO : labels) {
                GpsMmSwOrderVO orderVO = orderMap.get(labelVO.getOrderId());
                if (null == orderVO) {
                    log.error("没有找到对应的订单,{}", labelVO);
                    continue;
                }
                labelVO.setOrgId(orderVO.getOrgId());
                okList.add(BeanUtil.do2bo(labelVO, GpsMmSwOrderLabelDO.class));
            }
            if (CollectionUtils.isNotEmpty(okList)) {
                Lists.partition(okList, 50).forEach(subOrders -> {
                    log.info("开始同步GPS数据,size:{}", subOrders.size());
                    try {
                        gpsMmSwOrderLabelMapper.batchInsert(subOrders);
                        //根据条码的信息生成转包单
                        subcontractingOrderService.createZbdByBarcode(subOrders);
                    } catch (Exception e) {
                        log.error("同步GPS数据失败,voParam：{}", voParam, e);
                        throw new RuntimeException(e);
                    }
                });
            }
            if (!fullPage) {
                log.info("当前查询不满页,同步GPS数据完成,size:{}", labels.size());
                break;
            } else {
                log.info("当前查询满页,maxOrderId:{}", maxId);
            }
        }
    }


    public List<GpsMmSwOrderLabelDO> queryList(GpsMmSwOrderLabelVO wrap) {
        return gpsMmSwOrderLabelMapper.queryList(wrap);
    }

    public List<GpsMmSwOrderLabelDO> queryListByOrderId(Long orderId) {
        GpsMmSwOrderLabelVO wrap = new GpsMmSwOrderLabelVO();
        wrap.setUseState(0);
        wrap.setOrderId(orderId);
        return gpsMmSwOrderLabelMapper.queryList(wrap);
    }

}
